/*************************************************************************
    > File Name: 2.unix_tcp_client.c
    > Author: Ykk
    > Mail: 3393579535@qq.com 
    > Created Time: 2023年05月31日 星期三 21时23分29秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<stddef.h>
#include<string.h>
#include<unistd.h>
#include<sys/un.h>
#include<arpa/inet.h>
#include<sys/socket.h>

int main(int argc,char *argv[])
{
	unlink("ock.c");
	//创建unix流式套接字
	int cfd = socket(AF_UNIX,SOCK_STREAM,0);
	//绑定(如果不绑定就是隐式绑定)
	struct sockaddr_un myaddr;
	myaddr.sun_family = AF_UNIX;
	strcpy(myaddr.sun_path,"ock.c");
	int len1 = offsetof(struct sockaddr_un,sun_path) + strlen(myaddr.sun_path);
	if(bind(cfd,(struct sockaddr*)&myaddr,len1) < 0)
	{
		perror("bind");
		return 1;
	}
	//连接
	struct sockaddr_un seraddr;
	seraddr.sun_family = AF_UNIX;
	strcpy(seraddr.sun_path,"ock.s");
	int len2 = offsetof(struct sockaddr_un,sun_path) + strlen(seraddr.sun_path);
	connect(cfd,(struct sockaddr*)&seraddr,len2);	
	//读写
	while(1)
	{
		char buf[1500] = "";
		int n = read(STDIN_FILENO,buf,sizeof(buf));
		send(cfd,buf,sizeof(buf),0);
		memset(buf,0,sizeof(buf));
		n = recv(cfd,buf,sizeof(buf),0);
		if(n <= 0)
		{
			printf("err or server close\n");
			break;
		}
		else
		{
			printf("server:%s ==>%s\n",seraddr.sun_path,buf);
		}
	}
	//关闭
	close(cfd);
	return 0;
}
